import axios, {
  type AxiosError,
  type AxiosResponse,
  type InternalAxiosRequestConfig
} from "axios";
import { ContentTypeEnum } from "@/enum";
import { showToast, allowMultipleToast } from "vant";
import { showLoading } from '@/utils';
import { popWebViewController } from "@/utils/bridge";
import router from '@/router';
import { $t } from "@/locales";
import useAuthStore from "@/store/modules/auth";

allowMultipleToast();
const authStore = useAuthStore();
let tokenData: any = authStore.tokenData;
let tryTimes: any = {};
let loadingToast: any;

let request = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 30000,
  method: 'post',
  headers: {
    "Content-Type": ContentTypeEnum.JSON,
    client_id: 'app'
  }
})

request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  return config;
}, (error: AxiosError) => {
  error.message && showToast(error.message);
  return Promise.reject(error);
});

request.interceptors.response.use((response: AxiosResponse) => {
  const config: any = response.config;
  if (config.showLoading !== false) {
    loadingToast?.close();
  }
  const res = response.data;
  if (res.code === 0) {
    if (!config.plain) {
      res.data = res.data ? decrypt(res.data) : {};
    }
    console.log(`${config.url}返回值`, JSON.parse(JSON.stringify(res.data)));
    return res.data;
  } else if (res.code == 400002) { // token过期
    console.log(`${config.url}返回值`, res);
    tokenData = {};
    authStore.tokenData = {};
    if (tryTimes[response.config.url as string]) {
      showToast({
        message: '请重新登录',
        duration: 1500,
        onClose: () => {
        }
      });
      return Promise.reject(res);
    } else {
      tryTimes[response.config.url as string] = 1;
      return getTokenPro(true).then((result: any) => {
        tokenData = result;
        authStore.tokenData = result;
        return request(response.config);
      });
    }
  } else if (res.code == 400006) {
      authStore.resetStore();
      showToast({
        message: '账号在其他设备登录，您已被挤下线',
        duration: 1500,
        onClose: () => {
          popWebViewController();
        }
      });
  } else {
    console.log(`${config.url}返回值`, res);
    if (config.showToast !== false) {
      res.msg && showToast(res.msg);
    }
    return Promise.reject(res);
  }
}, (error: any) => {
  if (error.config.showLoading !== false) {
    loadingToast?.close();
  }
  if (error.config.showToast !== false) {
    showToast($t('common.requestError'));
  }
  return Promise.reject(error);
});


export default async function ajax(options: any) {
  const currentRoute: any = router.currentRoute.value;
  if ((currentRoute.meta.needLogin !== false || options.needLogin) && !tokenData.token) {
    await getTokenPro().then((res: any) => {
      tokenData = res;
      authStore.tokenData = res;
    });
  }
  tryTimes[options.url] = 0;
  console.log('入参', options.data);
  if (options.data && options.jwt !== false && !options.plain) {
    options.data = {
      encrypt: createDecrypt(options.data),
    };
  }
  if (options.showLoading !== false) {
    loadingToast?.close();
    loadingToast = showLoading();
  }
  return request(options);
}
